<?php
if(isset($_POST['token']))
{
  $token = filter_input(INPUT_POST,'token',FILTER_SANITIZE_STRING,FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH);
  if($token != $_SESSION['MczSession']->getToken())
  {
    die();
  }

  if(isset($_POST['action']))
  {
    $a = filter_input(INPUT_POST, 'action', FILTER_SANITIZE_STRING,FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH);
    switch($a)
    {
      /**
       * Podcast action
       */             
      case 'getpodcast':
        $url = filter_input(INPUT_POST,'url',FILTER_SANITIZE_URL);
        $myfeed = new PodcastReader($url);
        echo(json_encode(array('html'=>$myfeed->mkHtml())));
        die();
      case 'deletepodcast':
        $url = filter_input(INPUT_POST,'url',FILTER_SANITIZE_URL);
        $myfeed = new PodcastReader($url,FALSE);// do not init object on deletion
        echo(json_encode(array('html'=>$myfeed->delete())));
        die();
      case 'addpodcast':
        $url = filter_input(INPUT_POST,'url',FILTER_SANITIZE_URL);
        $myfeed = new PodcastReader($url);
        echo(json_encode(array('html'=>$myfeed->insert())));
        die();
      /**
       * Cue list actions
       */             
      case 'addToCue':
        die($_SESSION['CueList']->addItem($_POST['type'],$_POST['label'],$_POST['res_id']));
      case 'addMultipleToCue':
        $songIds = explode('|',$_POST['hash']);
        if(!empty($songIds))
        {
          foreach($songIds as $songId)
          {
            $songId = trim($songId);
            if(!empty($songId))
            {
              $_SESSION['CueList']->addItem('mczid','',$songId);
            }
          }
        }
        die(json_encode(true));
      case 'removeFromCue':
        die($_SESSION['CueList']->removeItem($_POST['id']));
      case 'updateCueOrder':
        die($_SESSION['CueList']->updateOrder($_POST['hash']));
      case 'getNext':
        if(!$_SESSION['MczSession']->can('play'))
        {
          die(json_encode(false));
        }
        die($_SESSION['CueList']->getNextItem());
      case 'getItemById':
        if(!$_SESSION['MczSession']->can('play'))
        {
          die(json_encode(false));
        }
        die($_SESSION['CueList']->getItemById($_POST['itemId']));
      case 'snapshotCueList':
        $newPlaylist = new PlayList('',array('name'=>$_POST['name'],'items'=>$_SESSION['CueList']->getItems()));
        $res = $newPlaylist->toDB();
        die(json_encode(array('response'=>$res,'list'=>PlayList::getPlaylists())));
      case 'scrobble':
        if(!$_SESSION['CueList']->scrobbleItem($_POST['trackId']))
        {
          $_SESSION['CueList']->scrobbleItem($_POST['trackId']);
        }

        die();
      /**
       *Playlists actions
       */
      case 'setPlsTitle':
        $playlist = new PlayList($_POST['plsId'],null);
        $title = trim($_POST['q']);
        if(!empty($title))
        {
          $playlist->setTitle(trim($_POST['q']));
          $playlist->toDB();
        }
        die($playlist->getTitle());
      case 'hashToPls':
        $songIds = explode('|',$_POST['hash']);
        if(!empty($songIds))
        {
          if(empty($_POST['id']))
          {
            $playlist = new PlayList('',array('name'=>$_POST['name'],'items'=>array()));
          }
          else
          {
            $playlist = new PlayList($_POST['id'],null);
          }
          foreach($songIds as $songId)
          {
            if(!empty($songId))
            {
              $song = new Song($songId);
              $playlist->addItem('mczid',$song->getLabel(),$songId);
            }
          }
          die(json_encode(array('response'=>$playlist->toDB(),'list'=>PlayList::getPlaylists())));
        }
        die();
      case 'listPls':
        die(PlayList::getPlaylistsSelect());
      case 'refreshPls':
        die(json_encode(array('list'=>PlayList::getPlaylists())));
      case 'deletePlaylist':
        $playlist = new PlayList($_POST['plsId'],null,false);
        $res = $playlist->delete();
        die(json_encode(array('response'=>$res,'list'=>PlayList::getPlaylists())));
      case 'displayPls':
        $playlist = new PlayList($_POST['plsId'],null);
        $res = $playlist->mkHtml();
        die(json_encode(array('response'=>$res)));
      case 'refreshCue':
        die(json_encode(array('html'=>$_SESSION['CueList']->mkHtml())));
      case 'addPlsToCue':
        $playlist = new PlayList($_POST['plsId'],null);
        $items = $playlist->getItems();
        foreach($items as $item)
        {
          $_SESSION['CueList']->addItem($item['type'],$item['label'],$item['res_id']);
        }
        die(json_encode(array('response'=>$_SESSION['CueList']->mkHtml())));
      case 'cueToPls':
        $playlist = new PlayList($_POST['plsId'],null);
        $playlist->setItems($_SESSION['CueList']->getItems());
        $playlist->toDB();
        $res = $playlist->mkHtml();
        die(json_encode(array('response'=>$res)));
      case 'stopPod':
        $playlist = new PlayList($_POST['plsId'],null);
        $playlist->stopPodcast();
        $playlist->toDB();
        $res = $playlist->mkHtml();
        die(json_encode(array('response'=>$res)));
      case 'startPod':
        $playlist = new PlayList($_POST['plsId'],null);
        $playlist->startPodcast();
        $playlist->toDB();
        $res = $playlist->mkHtml();
        die(json_encode(array('response'=>$res)));
      /**
       *Library
       */
      case 'refresh':
        die(json_encode(array('response'=>$_SESSION['Search']->mkHtml())));
      case 'addToLibrary':
        die(json_encode(ImportCue::add($_POST['url'])));
      case 'doSearch':
        $_SESSION['Search']->simple($_POST['keyword']);
        die(json_encode(array('response'=>$_SESSION['Search']->mkHtml())));
      case 'sortBy':
        $_SESSION['Search']->sortColumn($_POST['field']);
        die(json_encode(array('response'=>$_SESSION['Search']->mkHtml())));
      case 'offset':
        $_SESSION['Search']->setOffset($_POST['offset']);
        die(json_encode(array('response'=>$_SESSION['Search']->mkHtml())));
      /**
       *Single tag update (inline editing)
       */
      case 'setTag':
        $q = trim($_POST['q']);
        if(!empty($_POST['songId']))
        {
          $song = new Song($_POST['songId']);
          if(!empty($q))
          {
            if($_SESSION['MczSession']->can('mod_all'))
            {
              session_write_close();
              $song->setTag($_POST['tag'],$_POST['q']);
            }
            elseif($_SESSION['MczSession']->can('mod_own') and $song->owner() == $_SESSION['MczSession']->getLogin())
            {
              session_write_close();
              $song->setTag($_POST['tag'],$_POST['q']);
            }
          }
          die($song->getTag($_POST['tag']));
        }
        die();
      /**
       *Multiple tag update (ticked items)
       */
      case 'setTags':
        $songIds = explode('|',$_POST['songIds']);
        foreach($songIds as $songId)
        {
          $songId = trim($songId);
          if(!empty($songId))
          {
            $song = new Song($songId);
            if($_SESSION['MczSession']->can('mod_all'))
            {
              //session_write_close();
              $song->setTag($_POST['tag'],$_POST['tagValue']);
            }
            elseif($_SESSION['MczSession']->can('mod_own') and $song->owner() == $_SESSION['MczSession']->getLogin())
            {
              //session_write_close();
              $song->setTag($_POST['tag'],$_POST['tagValue']);
            }
          }
        }
        die(json_encode('ok'));
      /**
       *Multiple songs deletion
       */
      case 'deleteSongs':
        $songIds = explode('|',$_POST['songIds']);
        foreach($songIds as $songId)
        {
          $songId = trim($songId);
          if(!empty($songId))
          {
            $song = new Song($songId);
            if($_SESSION['MczSession']->can('del_all'))
            {
              $song->delete();
            }
            elseif($_SESSION['MczSession']->can('del_own') and $song->owner() == $_SESSION['MczSession']->getLogin())
            {
              $song->delete();
            }
          }
        }
        die(json_encode('ok'));
      /**
       *Display id3 form
       */
      case 'id3Form':
        $song = new Song($_POST['songId']);
        die(json_encode(array('response'=>$song->form())));
      case 'submitId3':
        if(!empty($_POST['songId']))
        {
          $song = new Song($_POST['songId']);
          $song->setTag('artist',$_POST['artist']);
          $song->setTag('title',$_POST['title']);
          $song->setTag('album',$_POST['album']);
          $song->setTag('genre',$_POST['genre']);
          $song->setTag('comment',$_POST['comment']);
          $song->setTag('year',$_POST['year']);
          $song->setTag('number',$_POST['number']);
          
          if($_SESSION['MczSession']->can('mod_all'))
          {
            $song->update();
            die(json_encode('ok'));
          }
          elseif($_SESSION['MczSession']->can('mod_own') and $song->owner() == $_SESSION['MczSession']->getLogin())
          {
            $song->update();
            die(json_encode('ok'));
          }
        }
        die(json_encode('ko'));
      /**
       *Session
       */
      case 'switchLang':
        $_SESSION['MczSession']->switchLang($_POST['lang']);
        die();
      case 'switchSkin':
        $_SESSION['MczSession']->switchSkin($_POST['skin']);
        die();
      case 'updateUserIds':
        $changes = false;
        if(!empty($_POST['lastfmPwd']))
        {
          $_SESSION['MczSession']->setLastfmPwd($_POST['lastfmPwd']);
          $changes = true;
        }
        if($_POST['lastfmUsr'] != $_SESSION['MczSession']->getLastfmUsr())
        {
          $_SESSION['MczSession']->setLastfmUsr($_POST['lastfmUsr']);
          $changes = true;
        }
        if(!empty($_POST['mczPwd']))
        {
          if($_SESSION['MczSession']->getLogin() != 'demo')
          {
            $_SESSION['MczSession']->setMczPwd($_POST['mczPwd']);
            $changes = true;
          }
        }
        if($changes)
        {
          die(json_encode(array('response'=>'ok','html'=>$_SESSION['MczSession']->mkPrefForm())));
        }
        else
        {
          die(json_encode(array('response'=>'ko')));
        }
      case 'groupForm':
        if($_SESSION['MczSession']->can('admin'))
        {
          $group = new Group($_POST['id']);
          die(json_encode(array('html'=>$group->form())));
        }
        die();
      case 'userForm':
        if($_SESSION['MczSession']->can('admin'))
        {
          $user = new User($_POST['id']);
          die(json_encode(array('html'=>$user->form())));
        }
        die();
      case 'switchUserStatus':
        if($_SESSION['MczSession']->can('admin') and $_POST['id'] != 'admin')
        {
          $user = new User($_POST['id']);
          die(json_encode($user->switchStatus()));
        }
        die();
      case 'changeGroup':
        if($_SESSION['MczSession']->can('admin') and $_POST['id'] != 'admin')
        {
          $user = new User($_POST['id']);
          die(json_encode($user->changeGroup($_POST['group'])));
        }
        die();
      case 'deleteUser':
        if($_SESSION['MczSession']->can('admin') and $_POST['id'] != 'admin')
        {
          $res = User::delete($_POST['id']);
          if($res === 1)
          {
            die(json_encode(array('response'=>'ok','html'=>User::listUsers())));
          }
          else
          {
            die(json_encode(array('response'=>'ko')));
          }
        }
        die();
      case 'addUser':
        if($_SESSION['MczSession']->can('admin') and $_POST['id'] != 'admin')
        {
          $res = User::createNew($_POST['id'],$_POST['password']);
          if($res === 1)
          {
            $user = new User($_POST['id']);
            die(json_encode(array('response'=>'ok','list'=>User::listUsers($_POST['id']),'form'=>$user->form())));
          }
          else
          {
            die(json_encode(array('response'=>STR_ERR_CANT_CREATE_USER)));
          }
        }
        die();
      case 'userChangePassword':
        if($_SESSION['MczSession']->can('admin') or $_POST['id'] == $_SESSION['MczSession']->getLogin())
        {
          $user = new User($_POST['id']);
          if($user->changePassword($_POST['password']))
          {
            die(json_encode(array('response'=>'ok')));
          }
          else
          {
            die(json_encode(array('response'=>'ko')));
          }
          die();
        }
        die();
      case 'updateGroupRights':
        if($_SESSION['MczSession']->can('admin'))
        {
          Group::setRight($_POST['id'],$_POST['right'],$_POST['value']);
        }
        die();
      case 'addGroup':
        if($_SESSION['MczSession']->can('admin'))
        {
          if(Group::createNew($_POST['name']))
          {
            $group = new Group($_POST['name']);
            die(json_encode(array('response'=>'ok','list'=>Group::listGroups($_POST['name']),'form'=>$group->form())));
          }
          else
          {
            die(json_encode(array('response'=>'ko')));
          }
        }
        die();
      case 'deleteGroup':
        if($_SESSION['MczSession']->can('admin'))
        {
          if(Group::delete($_POST['id']))
          {
            die(json_encode(array('response'=>'ok','list'=>Group::listGroups())));
          }
          else
          {
            die(json_encode(array('response'=>'ko')));
          }
        }
        die();
      default:
        die();
    }
  }
  else
  {
    die();
  }
}
else
{
  die(json_encode(date("H:i",time())));
}
?>
